package org.mc.resolver;

import org.apache.commons.lang.StringUtils;
import org.mc.utils.CookieUtils;
import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import javax.servlet.http.HttpServletRequest;

/**
 * Created by lenovo on 2018/4/16.
 */
public class AuthUserIdResolver implements HandlerMethodArgumentResolver {

    @Override
    public boolean supportsParameter(MethodParameter methodParameter) {
        return methodParameter.getParameterAnnotation(AuthUserId.class) != null;
    }

    @Override
    public Object resolveArgument(MethodParameter methodParameter, ModelAndViewContainer modelAndViewContainer, NativeWebRequest nativeWebRequest, WebDataBinderFactory webDataBinderFactory) throws Exception {
        HttpServletRequest httpServletRequest = nativeWebRequest.getNativeRequest(HttpServletRequest.class);
        String token = httpServletRequest.getHeader("userId");
        if (StringUtils.isNotBlank(token)) {
            return token;
        }
        token = CookieUtils.getCookieByName(httpServletRequest, "userId");
        if (StringUtils.isNotBlank(token)) {
            return Long.valueOf(token);
        }
        return null;
    }
}
